

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.utils import timezone

from meiduo_mall.utils.secret import SecretOauth
from apps.users.models import User


# 自定义认证后端
class UsernameMobileAuthBackend(ModelBackend):

    # 重写认证后端方法
    def authenticate(self, request, username=None, password=None, **kwargs):

        try:
            user = User.objects.get(username=username)
        except Exception as e:
            print(e)
            try:
                user = User.objects.get(mobile=username)
            except Exception as e:
                print(e)
                return None

        # 如果是商城页面登陆8080，request是一个请求对象
        # 如果是管理站点页面登陆8081 ，request是一个None
        if request is None and not user.is_staff:
            return None

        if user.check_password(password):
            user.last_login = timezone.localtime()
            user.save()
            return user


    # 封装生成验证链接的类：
    # 过程拿到用户的id和email,然后对两个数据进行加密，拼接完整的激活路径，返回。

def generate_verify_email_url(request):

    # 1：拿到用户的id和email
    data_dict = {
        "user_id": request.user.id,
        "email" : request.user.email,
    }

    # 2:字典进行加密
    dumps_data = SecretOauth().dumps(data_dict)

    # 3:拼接完整的激活路径settings.EMAIL_VERIFY_URL是：
    verify_url = settings.EMAIL_VERIFY_URL + dumps_data

    return verify_url





